package hr.riteh.assistivecommunicator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ImportActivity extends Activity implements ListChooserDialog.OnChosenListener
{
	private TextView mTextViewChosenPackageFullPath;
	private Button mButtonImport;

	private List<File> mFoundPackages = new ArrayList<File>();
	private FileListAdapter mAdapter = new FileListAdapter(mFoundPackages);
	private ListChooserDialog mPackageChooserDialog;
	private File mChosenPackage;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_import);

		// Retrieve references to layout views
		mTextViewChosenPackageFullPath = (TextView) findViewById(R.id.textView_chosenfilepath);
		mButtonImport = (Button) findViewById(R.id.button_import);

		// Scan external storage for package files
		FileUtils.findFilesRecursively(mFoundPackages, Environment.getExternalStorageDirectory(), Package.FILE_EXTENSION);

		// Create dialog for choosing package file
		mPackageChooserDialog = new ListChooserDialog(this);
		mPackageChooserDialog.setOnChosenListener(this);
		mPackageChooserDialog.setAdapter(mAdapter);
		mPackageChooserDialog.setTitle("Choose package file");
	}

	public void onChooseFileClicked(View view)
	{
		// Show dialog for choosing package to import
		mPackageChooserDialog.show();
	}

	@Override
	public void onChosen(int position)
	{
		// Get reference to selected file
		mChosenPackage = mFoundPackages.get(position);

		// Display full file path on TextView
		mTextViewChosenPackageFullPath.setText(mChosenPackage.getAbsolutePath());

		// Enable 'Import' button
		mButtonImport.setEnabled(true);
	}

	public void onImportClicked(View view)
	{
		// Prepare
		Database database = new Database(this);
		FileResourceManager fileResourceManager = new FileResourceManager(this);

		// Actually do import
		Package.doImport(mChosenPackage, database, fileResourceManager);
	}

	public void onDoneClicked(View view)
	{
		// Close (this) activity
		finish();
	}
}
